package exam.wangyi.spring.S4;

import java.util.*;

public class Main {

    public static int m;
    public static int n;
    public static int resMinTime = Integer.MAX_VALUE;
    public static int[][] graph;
    public static int[][] minTime;
    public static int[] dx = {0, 0, 1};
    public static int[] dy = {-1, 1, 0};

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        m = sc.nextInt();
        n = sc.nextInt();
        graph = new int[m][n];
        minTime = new int[m][n];
        for (int i=0; i<m; ++i)
            Arrays.fill(minTime[i], Integer.MAX_VALUE);
        for (int i=0; i<m; ++i) {
            sc.nextLine();
            for (int j=0; j<n; ++j) {
                graph[i][j] = sc.nextInt();
            }
        }
        dfs(0, 0, 0);
        System.out.println(resMinTime);
    }

    public static void dfs(int x, int y, int time) {
        if (time >= minTime[x][y] || time >= resMinTime)
            return;
        minTime[x][y] = time;
        if (x == m-1 && y == n-1) {
            resMinTime = time;
            return;
        }
        int t = graph[x][y];
        graph[x][y] = -1;
        for (int i=0; i<3; ++i) {
            int nx = x + dx[i], ny = y + dy[i];
            if (nx >= 0 && nx < m && ny >= 0 && ny < n && graph[nx][ny] >= 0) {
                if (graph[nx][ny] != t)
                    dfs(nx, ny, time+2);
                else
                    dfs(nx, ny, time+1);
            }
        }
        graph[x][y] = t;
    }
}